<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form
          @submit.native.prevent
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="协议名称" prop="title">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入协议名称"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-select v-model="queryParams.type" placeholder="请选择">
              <el-option
                v-for="dict in behavior_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row :gutter="10" class="mb10">
      <el-col :span="1.5">
        <el-button type="primary" @click="handleAdd">新增协议</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" @click="batchRemand">移入推荐</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" @click="batchDelete">移出推荐</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-row class="mb8">
      <el-table
        v-loading="loading"
        :data="list"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="序号" width="50" align="center" type="index" />
        <el-table-column label="协议名称" align="center" prop="title" />
        <el-table-column label="作者" align="center">
          <span>系统管理员</span>
        </el-table-column>
        <el-table-column label="协议类型" align="center" prop="recommend">
          <template #default="scope">
            <dict-tag :options="behavior_type" :value="scope.row.type" />
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="hidden">
          <template #default="scope">
            <dict-tag :options="content_hidden" :value="scope.row.hidden" />
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          width="170"
        >
          <template #default="scope">
            <span>{{ parseTime(scope.row.gmtCreate) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <a
              href="javascript:;"
              style="color: #358de5; text-decoration: none; margin-right: 10px"
              @click="handleUpdate(scope.row, 1)"
              >查看</a
            >
            <a
              href="javascript:;"
              style="color: #358de5; text-decoration: none; margin-right: 10px"
              @click="handleUpdate(scope.row, 2)"
              >编辑</a
            >
            <a
              href="javascript:;"
              style="color: #f56c6c; text-decoration: none; margin-right: 10px"
              @click="handleDelete(scope.row)"
              >删除</a
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form
        @submit.native.prevent
        :model="form"
        :rules="rules"
        ref="userRef"
        label-width="120px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="协议类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择">
                <el-option
                  v-for="item in behavior_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="协议名称" prop="title">
              <el-input
                v-model="form.title"
                placeholder="请输入"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="是否展示">
              <el-radio-group v-model="form.recommend">
                <el-radio
                  v-for="dict in content_hidden"
                  :key="dict.value"
                  :label="Number(dict.value)"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="发布时间" prop="publicationDate">
              <el-date-picker
                v-model="form.publicationDate"
                type="datetime"
                placeholder="选择日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="作者" prop="auther">
              <el-input
                v-model="form.auther"
                placeholder="请输入"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="图片" prop="imageUrls" required>
              <ImageUpload
                v-model="form.imageUrls"
                :materialType="1"
                :limit="2"
                :fileType="['png', 'jpg', 'jpeg']"
                :isPreview="true"
              ></ImageUpload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="图文内容" prop="content" required>
              <Editor v-model="form.content" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer v-if="title !== '详情'">
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="agreement">
import {
  queryBehaviorPage,
  addBehavior,
  editBehavior,
  behaviorExport,
  showbehaviorByHome,
  hideBehaviorByHome,
  deleteBehavior,
} from "@/api/behavior";
const { proxy } = getCurrentInstance();
const { content_hidden, behavior_type } = proxy.useDict(
  "content_hidden",
  "behavior_type"
);
const list = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const data = reactive({
  form: {
    id: undefined,
    title: "",
    type: undefined,
    recommend: 0,
    content: undefined,
    imageUrls: null,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 1000,
    title: undefined,
    type: undefined,
  },
  rules: {
    title: [{ required: true, message: "协议名称不能为空", trigger: "blur" }],
    type: [{ required: true, message: "价格不能为空", trigger: "blur" }],
    content: [{ required: true, message: "内容不能为空", trigger: "blur" }],
    imageUrls: [{ required: true, message: "图片不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 选择条数  */
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 查询用户列表 */
const getList = () => {
  loading.value = true;
  queryBehaviorPage(
    proxy.addDateRange(queryParams.value, dateRange.value)
  ).then((res) => {
    loading.value = false;
    list.value = res.rows;
    total.value = Number(res.total);
  });
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  queryParams.value = {
    pageNum: 1,
    pageSize: 1000,
    title: undefined,
    type: undefined,
  };
  handleQuery();
};

/** 批量显示 */
const batchRemand = async () => {
  if (ids.value.length == 0) {
    proxy.$modal.msgWarning("请选择操作内容");
    return false;
  }
  let result = await showbehaviorByHome(ids.value.toString());
  if (result.code == 200) {
    getList();
    proxy.$modal.msgSuccess("操作成功");
  }
};

/** 批量隐藏 */
const batchDelete = async () => {
  if (ids.value.length == 0) {
    proxy.$modal.msgWarning("请选择操作内容");
    return false;
  }
  let result = await hideBehaviorByHome(ids.value.toString());
  if (result.code == 200) {
    getList();
    proxy.$modal.msgSuccess("操作成功");
  }
};

/** 导出按钮操作 */
const handleExport = async () => {
  proxy.$modal.loading("文件导出中，请稍候...");
  let result = await behaviorExport();
  const blob = new Blob([result]);
  let link = document.createElement("a");
  link.href = URL.createObjectURL(blob);
  link.download = "书籍列表_" + new Date().getTime() + ".xlsx";
  link.click();
  proxy.$modal.closeLoading();
};

/** 重置操作表单 */
const reset = () => {
  form.value = {
    id: null,
    title: "",
    type: undefined,
    recommend: 0,
    content: undefined,
    imageUrls: null,
  };
  proxy.resetForm("userRef");
};

const handleAdd = () => {
  title.value = "新增";
  reset();
  open.value = true;
};
/** 取消按钮 */
const cancel = () => {
  open.value = false;
  changeScore.value = false;
  reset();
};

/** 下移按钮操作 */
const handleHide = (row) => {
  if (row.recommendSort < 1) {
    proxy.$modal.msgWarning("已是最低排名，无法下移");
    return false;
  }
  let recommendSort = row.recommendSort - 1;
  proxy.$modal
    .confirm("确认将" + row.title + "协议往下移")
    .then(() => {
      return editBehavior({ id: row.id, recommendSort: recommendSort });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("下移成功");
    })
    .catch(() => {});
};

/** 上移按钮操作 */
const handleShow = (row) => {
  let recommendSort = row.recommendSort + 1;
  proxy.$modal
    .confirm("确认将" + row.title + "协议往上移")
    .then(() => {
      return editBehavior({ id: row.id, recommendSort: recommendSort });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("上移成功");
    })
    .catch(() => {});
};

/** 删除按钮操作 */
const handleDelete = (row) => {
  proxy.$modal
    .confirm("是否确认要删除" + row.title + "协议")
    .then(() => {
      return deleteBehavior(row.id);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
};
/** 修改按钮操作 */
const handleUpdate = (row, type) => {
  reset();
  title.value = type == 1 ? "详情" : "编辑";
  form.value = {
    ...row,
  };
  open.value = true;
};

watch(
  () => open.value,
  (val) => {
    if (val) {
      form.value.imageUrls = form.value.imageUrls
        ? JSON.parse(form.value.imageUrls)
        : [];
    }
  }
);

/** 提交按钮 */
const submitForm = () => {
  proxy.$refs["userRef"].validate((valid) => {
    if (valid) {
      form.value.imageUrls = JSON.stringify(
        form.value.imageUrls ? form.value.imageUrls.split(",") : []
      );
      if (form.value.id) {
        editBehavior(form.value).then((response) => {
          proxy.$modal.msgSuccess("编辑成功");
          open.value = false;
          getList();
        });
      } else {
        addBehavior(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
};

getList();
</script>
        <style lang='scss' scoped>
</style>
        